import Product, { IProduct } from '../models/Product';
import { Request, Response } from 'express';
import upload from '../middlewares/upload';
import moment from 'moment';

// 新增商品
export const addProduct = async (req: Request, res: Response) => {
    upload.single('image')(req, res, async (error: any) => {
        if (error) {
            return res.status(500).json({ message: error.message });
        }

        try {
            const { title = '', description = '', categories = [], tags = [], price = 0, stock = 0, addDraws = 0, canBalanceBuy = false, needsBalance } = req.body;
            const imagePath = req.file ? req.file.path : null; // 获取上传的图片路径

            const product = new Product({
                title,
                description,
                images: imagePath ? [imagePath] : [], // 如果有图片则添加
                categories,
                tags,
                price,
                stock,
                addDraws,
                canBalanceBuy,
                needsBalance,
                createdAt: moment().format('YYYY-MM-DD HH:mm:ss'),
                updatedAt: moment().format('YYYY-MM-DD HH:mm:ss')
            });

            await product.save();
            res.status(201).json({
                status: 'ok',
                message: '新增商品成功！',
                data: product
            });
        } catch (error: any) {
            res.status(500).json({ message: error.message });
        }
    });
};

// 删除商品
export const deleteProduct = async (req: Request, res: Response) => {
    try {
        const { id } = req.params;
        const product = await Product.findByIdAndDelete(id);
        if (!product) {
            return res.status(404).json({ message: '商品未找到' });
        }
        res.json({ message: '商品删除成功' });
    } catch (error: any) {
        res.status(500).json({ message: error.message });
    }
};

// 修改商品
export const updateProduct = async (req: Request, res: Response) => {
    upload.single('image')(req, res, async (error: any) => {
        if (error) {
            return res.status(500).json({ message: error.message });
        }

        try {
            const { _id } = req.body;
            let updateData = req.body;

            // 如果有新的图片上传，则更新图片路径
            if (req.file) {
                updateData.image = req.file.path;
            } else {
                delete updateData.image
            }

            // 更新 updatedAt 字段
            updateData.updatedAt = moment().format("YYYY-MM-DD HH:mm:ss");

            const updatedProduct = await Product.findByIdAndUpdate(_id, updateData, { new: true });
            if (!updatedProduct) {
                return res.status(404).json({ message: '商品未找到' });
            }

            res.json({
                status: 'ok',
                message: '更新商品成功！',
                data: updatedProduct
            });
        } catch (error: any) {
            res.status(500).json({ message: error.message });
        }
    });
};

// 根据 ID 查询商品
export const getProductById = async (req: Request, res: Response) => {
    try {
        const { id } = req.params;
        const product = await Product.findById(id);
        if (!product) {
            return res.status(404).json({ message: '商品未找到' });
        }
        res.json(product);
    } catch (error: any) {
        res.status(500).json({ message: error.message });
    }
};

// 分页查询所有商品
export const getProducts = async (req: Request, res: Response) => {
    try {
        const page = parseInt(req.query.page as string) || 1;
        const limit = parseInt(req.query.limit as string) || 10;
        const skipIndex = (page - 1) * limit;
        const products = await Product.find().skip(skipIndex).limit(limit);
        const total = await Product.countDocuments();
        res.json({
            total,
            page,
            limit,
            data: products
        });
    } catch (error: any) {
        res.status(500).json({ message: error.message });
    }
};
